package by.ostrovsky.webhousingsystem.dao.implementation;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;

import by.ostrovsky.webhousingsystem.dao.implementation.idao.IOperateDAO;
import by.ostrovsky.webhousingsystem.dao.implementation.idao.IReadDAO;
import by.ostrovsky.webhousingsystem.exception.CommonException;
import by.ostrovsky.webhousingsystem.exception.OperationErrorException;
import by.ostrovsky.webhousingsystem.hibernate.HibernateUtil;
import by.ostrovsky.webhousingsystem.hibernate.entity.WorkPlan;

public class MySQLWorkPlanDAO implements IOperateDAO<List<WorkPlan>, Boolean>,
		IReadDAO<WorkPlan>{
	private static Logger logger = Logger.getLogger(MySQLWorkPlanDAO.class);

	@Override
	public List<WorkPlan> readAll() throws CommonException {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			@SuppressWarnings("unchecked")
			List<WorkPlan> list = session.createCriteria(WorkPlan.class).list();
			session.getTransaction().commit();
			session.close();

			return list;
		} catch (HibernateException e) {
			throw new OperationErrorException();
		}
	}

	@Override
	public Boolean update(List<WorkPlan> object) throws CommonException {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			for (WorkPlan wp : object) {
				try {
					session.update(wp);
				} catch (HibernateException ex) {
					logger.error(ex);
				}
			}
			session.getTransaction().commit();
			session.close();
			return true;
		} catch (HibernateException e) {
			logger.error(e);
			throw new OperationErrorException();
		}
	}

	@Override
	public Boolean create(List<WorkPlan> workPlan) throws CommonException {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			for (WorkPlan wp : workPlan) {
				try {
					session.save(wp);
				} catch (HibernateException ex) {
					logger.error(ex);
				}
			}
			session.getTransaction().commit();
			session.close();
			return true;
		} catch (HibernateException e) {
			logger.error(e);
			throw new OperationErrorException();
		}
	}

	@Override
	public Boolean delete(List<WorkPlan> list) throws CommonException {
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			for (WorkPlan wp : list) {
				try {
					session.delete(wp);
				} catch (HibernateException ex) {
					logger.error(ex);
				}
			}
			session.getTransaction().commit();
			session.close();
			return true;
		} catch (HibernateException e) {
			throw new OperationErrorException();
		}
	}

	@Override
	public WorkPlan read(WorkPlan object) throws CommonException {
		// TODO Auto-generated method stub
		return null;
	}
}
